import axios from 'axios'
import { ElNotification } from 'element-plus'
import { getToken, setToken } from '@/utils/auth'

// 是否显示重新登录
export let isRelogin = { show: false };

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: import.meta.env.VITE_APP_BASE_API,
  // 超时
  timeout: 10000
})

// request拦截器
service.interceptors.request.use(config => {
  if (getToken()) {
    config.headers['SYSTOKEN'] = getToken()
  }
  return config
}, error => {
    Promise.reject(error)
})


service.interceptors.response.use(
  response => {
    const SysToken = getToken()
    if (SysToken) {
      setToken(SysToken)
    }

    const res = response.data
    if (res.statusCode !== 200) {
      switch (res.statusCode) {
        case 403:
          ElNotification.error({
            title: '您无权进行此操作，请求执行已拒绝',
            duration: 3000
          })
          break
        default:
          ElNotification.error({
            title: res.message
          })
          break
      }
    }

    return res
  },
  error => {
    ElNotification.error({
      title: '请求接口失败',
      duration: 3000
    })
    return Promise.reject(error)
  }
)
export default service
